package net.lab1024.sa.gateway.filter;

import com.alibaba.fastjson2.JSON;
import net.lab1024.sa.gateway.handler.GatewayCoreHandler;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.LinkedHashSet;

@Component
public class CoreHandlerFilter implements GlobalFilter, Ordered {
    private final GatewayCoreHandler coreHandler;

    public CoreHandlerFilter(GatewayCoreHandler coreHandler) {
        this.coreHandler = coreHandler;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取原始请求路径，避免StripPrefix过滤器的影响
        LinkedHashSet<URI> originalUris = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        String originalPath = (originalUris != null && !originalUris.isEmpty())
                ? originalUris.iterator().next().getRawPath()
                : exchange.getRequest().getURI().getRawPath();

        // 不处理原始路径为/admin开头的请求，让这些请求走正常的路由转发
        // 由于StripPrefix=1过滤器会去掉第一层路径，所以我们需要检查原始路径
        if (originalPath.startsWith("/admin/")) {
            return chain.filter(exchange);
        }

        // 1. 前置处理（如流量染色、设备指纹）已通过其他过滤器完成
        // 2. 调用核心处理器处理业务逻辑
        return coreHandler.handle(exchange)
                .flatMap(result -> {
                    // 如果结果为空，说明不需要处理，继续走路由转发
                    if (result == null) {
                        return chain.filter(exchange);
                    }
                    // 3. 将处理结果写入响应
                    exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return exchange.getResponse().writeWith(Mono.just(
                            exchange.getResponse().bufferFactory().wrap(JSON.toJSONBytes(result))
                    ));
                });
    }

    @Override
    public int getOrder() {
        return 100; // 确保在限流、染色等过滤器之后执行
    }
}